<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Facades\MoneyPlatformRequestFacade;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class RepayMoneyNotifyJobQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    protected $record_id;

    /**
     * Create a new job instance.
     * RepayMoneyNotifyJobQueue constructor.
     * @param $record_id
     */
    public function __construct($record_id)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_MONEY_NOTIFY);
        $this->record_id = $record_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $recordInfo = RepayRecord::find($this->record_id);
        if($recordInfo->status != RepayRecord::STATUS_FOUR && $recordInfo->common->status != RepayRecordCommon::STATUS_FOUR){
            $this->delete();
            return;
        }
        if($recordInfo->relationSummary->loan_channel != SettingChannel::CHANNEL_OLD_GUANGDA
            || $recordInfo->common->money_notify_status == RepayRecordCommon::MONEY_NOTIFY_STATUS_TWO
            || $recordInfo->common->money_notify_status == RepayRecordCommon::MONEY_NOTIFY_STATUS_FOUR){
            $this->delete();
            return;
        }
        //请求接口
        $tradeNo = RepaySummary::createTradeNo($recordInfo->uid,'money');
        $recordInfo->trade_no = $tradeNo;
        $loan_id = $this->getLoanId($recordInfo);
        if(!$loan_id){
            return;
        }
        $recordInfo->loan_id = $loan_id;
        $this->setMoney($recordInfo);
        $this->delete();
    }

    protected function getLoanId(RepayRecord $recordInfo){
        $channel_user_id = User::where('id',$recordInfo->uid)->value('channel_user_id');
        $array = [
            'uid' => $channel_user_id,
            'outTradeId' => $recordInfo->relationSummary->transfer_loan_id
        ];
        $data = MoneyPlatformRequestFacade::getLoanId($array);
        Log::debug('money_notify:' . json_encode($data,JSON_UNESCAPED_UNICODE));
        if(isset($data['data'])){
            $loan_id = isset($data['data']['loanId']) ? $data['data']['loanId'] : '';
            if($loan_id){
                return $loan_id;
            }
        }
        return false;
    }

    /**
     * Description:请求资方接口
     * Author:lijiafei
     * @param $recordInfo RepayRecord 表的model
     * @param $tradeNo 1 逐期还款 2 全部还清
     * @return bool
     */
    private function setMoney($recordInfo){
        $questData = $this->getMoneyRequestData($recordInfo);
        if(!$questData){
            return false;
        }
        $moneyData['loanId'] = $recordInfo->loan_id;
        $moneyData['merOrderNo'] = $recordInfo->trade_no;
        $moneyData['currentPeriod'] = $questData['period'];
        $moneyData['totalAmt'] = $questData['totalAmt']; //还款总金额
        $moneyData['principalAmt'] = $questData['amount']; //本金
        $moneyData['interestAmt'] = $questData['lending_money']; //利息
        $moneyData['serviceAmt'] = $questData['repayment_money']; //服务费
        $moneyData['penaltyAmt'] = $questData['fines_money']; //罚息
        $moneyData['operateStatus'] = $questData['operateStatus'];
        $res = MoneyPlatformRequestFacade::setMoneyRepay($moneyData,2);
        if(isset($res['data']['resultRepayId'])){
            $update = [
                'money_notify_status' => RepayRecordCommon::MONEY_NOTIFY_STATUS_TWO,
                'money_notify_trade_no' => $recordInfo->trade_no,
                'money_notify_third_record_id' => $res['data']['resultRepayId']
            ];

            RepaySummary::where('id',$recordInfo->summary_id)->update(['loan_id'=>$recordInfo->loan_id]);
        }else{
            $update = [
                'money_notify_status' => RepayRecordCommon::MONEY_NOTIFY_STATUS_THREE,
                'money_notify_trade_no' => $recordInfo->trade_no,
                'money_notify_third_record_id' => isset($res['data']['resultRepayId'])?$res['data']['resultRepayId']:''
            ];
        }
        $update['response_data'] = json_encode($res,JSON_UNESCAPED_UNICODE);
        RepayRecordCommon::where('id',$recordInfo->common->id)->update($update);
        return true;
    }

    /**
     * 封装资方的接口请求数据
     * @param $recordInfo RepayRecord repay_record的model
     * @return  array|boolean data
     */
    protected function getMoneyRequestData($recordInfo){
        $operateStatus = 'R';//操作状态(正常还款R,提前结清J,提前还当期T)
        if($recordInfo->pay_off == RepayRecord::PAY_OFF_ONE){
            //判断是否逾期
            $day_num = count_days($recordInfo->repay_date,$recordInfo->normal_date);
            //还当期
            if($day_num < 0){
                $operateStatus = 'T';//提前还当期T
            }
            $data = RepaySummary::mapMoneyDataFromThirdApi($recordInfo->loan_id,$recordInfo->period);
            Log::debug('money_notify_plan' . json_encode($data,JSON_UNESCAPED_UNICODE));
            if(!$data){
                return false;
            }
            $status = $data['status'];
            $status = RepayRecordMoney::getMoneyPlanStatus($status);
            if($status){
                $update = [
                    'money_notify_status' => RepayRecordCommon::MONEY_NOTIFY_STATUS_FOUR,
                    'money_notify_trade_no' => $recordInfo->trade_no,
                    'money_notify_third_record_id' => 'over',
                ];
                RepayRecordCommon::where('id',$recordInfo->common->id)->update($update);
                return false;
            }
            $amount = $data['principalAmount'];
            $lending_money = $data['interestAmount'];
            $repayment_money = $data['serviceAmount'];
            $fines_money = $data['penaltyAmount'];
            $total = $data['totalAmount'];
            $period = $data['currentPeriod'];
        }elseif($recordInfo->pay_off == RepayRecord::PAY_OFF_TWO){
            //提前结清
            $operateStatus = 'J';
            $period = RepayRecord::where('summary_id',$recordInfo->summary_id)->where('pay_off',RepayRecord::PAY_OFF_ONE)->where('status','<>',RepayRecord::STATUS_FOUR)->orderBy('period','asc')->value('period');
            $data = MoneyPlatformRequestFacade::getRepaymentPlan($recordInfo->loan_id);
            if(empty($data['data'])){
                return false;
            }else{
                $data = $data['data'];
                $total = $data['totalAmount'];
                $amount = $data['principalAmount'];
                $lending_money = $data['interestAmount'];
                $repayment_money = $data['serviceAmount'];
                $fines_money = $data['penaltyAmount'];
            }

        }else{
            return false;
        }
        $data = [
            'period' => $period,
            'totalAmt' => $total,//总金额
            'amount' => $amount,//本金
            'lending_money' => $lending_money,//利息
            'repayment_money' => $repayment_money,//提前结清手续费
            'fines_money' => $fines_money,//罚息
            'operateStatus' => $operateStatus,
        ];
        return $data;
    }

}
